import * as auth from '@/utils/auth'
import * as wxSdk from '@/utils/sdk/src/wx'
import * as utils from './index.js'
import {
  locAccount,
  locPassword,
  locSharePath,
  locUrlToken
} from '@/utils/locStore/data.ts'
/**
 * 获取环境
 */
export function getEvn() {
  var ua = navigator.userAgent.toLowerCase()
  const href = window.location.href
  // 必须用 ==
  if (href.includes('evn=H5')) {
    return 'h5'
  } else if (ua.match(/MicroMessenger/i)) {
    // 微信环境
    return 'wx'
  } else if (href.includes('evn=TEST')) {
    return 'test'
  }
  return 'other'
}

// 获取授权参数
export function loginByOAuth2(data) {
  return auth.toGetToken(true).then(() => {
    return uni.$api.public.loginByOAuth2(data)
  })
}

export function initWx(type = 'init') {
  console.log('进入initWx函数------------------------------------')
  const loc = window.location

  if (type === 'init') {
    // return auth.toGetUserInfo(true) // 获取用户信息并存储
    // const token = auth.getLocToken()
    // if (token) {
    //   auth.getUserInfo(true) // 获取用户信息并存储
    //   return wxSdk.initSDK()
    // } else {
    return auth.toGetToken(true).then(() => {
      return wxSdk.initSDK()
    })
    // }
  }

  // debugger
  const hash = loc.hash
  let url = `${loc.origin}${loc.pathname}?WXTIME=${+new Date()}`
  if (hash) {
    url = url + hash
  }
  const isShare = window.location.href.includes('isShare=1')
  if (isShare) {
    const sharePath = window.location.hash.replace('#', '')
    locSharePath.set(sharePath)
  }

  if (type === 'init' && !isShare) {
    window.location.href = url
  } else if (type === 'toAuth') {
    return new Promise((resolve, reject) => {
      const data = {
        url: url
      }
      const query = {
        type: 'weixin',
        data: JSON.stringify(data)
      }
      loginByOAuth2(query)
        .then((res) => {
          const url = res.redirect_url
          window.location.href = url
          // return res
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
}

// 微信环境 处理登录
// flag 控制是否 直接 跳转授权
export function handleWx(flag = false, onClick = false) {
  const loc = window.location
  const href = loc.href
  const token = auth.getLocToken()
  const evn = getEvn()
  if (evn === 'wx' && token && !flag) {
    return auth.toGetUserInfo(true) // 获取用户信息并存储
    // return wxSdk.initSDK()
  }
  const urlQuery = utils.param2Obj()
  let url = href.includes('forceUrl=1')
    ? `${loc.origin}${loc.pathname}${loc.search}${
        href.includes('WXTIME=') ? '' : '&WXTIME=' + +new Date()
      }${loc.hash}`
    : `${loc.origin}${loc.pathname}?pwy=${urlQuery.pwy}&WXTIME=${+new Date()}`
  if (href.includes('GD=1')) {
    url = url + '&GD=1'
  }

  const data = {
    url: url
  }
  const query = {
    type: 'weixin',
    data: JSON.stringify(data)
  }

  const isShare = window.location.href.includes('isShare=1')
  if (isShare) {
    const sharePath = window.location.hash.replace('#', '')
    locSharePath.set(sharePath)
  }

  if (onClick) {
    return new Promise((resolve, reject) => {
      loginByOAuth2(query)
        .then((res) => {
          const url = res.redirect_url
          window.location.href = url
          // return res
        })
        .catch((err) => {
          reject(err)
        })
    })
  } else {
    return Promise.resolve()
  }
}

export function handleAllEnv() {
  const evn = getEvn()
  const NODE_ENV = process.env.VUE_APP_ENV
  if (NODE_ENV === 'development') {
    // 开发环境不跳转
    return Promise.resolve()
  }
  if (evn === 'wx') {
    return initWx()
  }
  return Promise.resolve()
}

// 特殊处理 删除url 参数并存储 本地
function handleUrlQueryDel() {
  const query = utils.param2Obj()
  if (query.CCBTIMESTAMP) {
    utils.removeUrlParams([
      'oldtk',
      'CCBSIGN',
      'CCBTIMESTAMP',
      'param',
      'sign',
      'user_id'
    ])
    auth.saveUrlQuery(query)
  }
}

// 处理环境
const replaceUrl = ['index/home']
export const handleEvn = async (cb) => {
  const href = window.location.href
  // 兼容旧地址
  for (let i = 0; i < replaceUrl.length; i++) {
    if (href.indexOf(replaceUrl[i]) > -1) {
      window.location.href = href.replace(replaceUrl[i], '')
      window.location.reload()
      return
    }
  }

  handleUrlQueryDel()
  handelShareQuery()
  setTimeout(async () => {
    await auth.toGetBaseSet(true)
    await handleAllEnv()
    cb && cb()
  }, 100)
}

function handelShareQuery() {
  handleMate()
  const evn = getEvn()
  let paramUrl = window.location.hash
  if (paramUrl === '#/' || '') {
    paramUrl = window.location.search
  }
  const param = utils.param2Obj(paramUrl)
  const {
    shareUrl,
    account,
    password,
    tokenId,
    token,
    pwy,
    backUrl,
    cityId,
    regionName
  } = param
  account && locAccount.set(account)
  password && locPassword.set(password)
  console.log(account, '1account', auth.getLocAccount())
  if (account !== auth.getLocAccount() && account) {
    console.log('商户号不一样，清楚缓存')

    auth.removeAll()
    auth.clearAll()
  }
  const urlToken = tokenId || token || ''
  if (urlToken) {
    replaceUrlToken() // 
    const _locUrlToken = locUrlToken.get()
    if (_locUrlToken !== urlToken) {
      // 只获取一次 url 上的token
      auth.saveToken(urlToken)
      locUrlToken.set(urlToken)
      auth.getUserInfo(true, '1')
    }
  }
  if (backUrl) {
    auth.setBackUrl(backUrl)
  }

  console.log('处理handelShareQuery')
  if (cityId && regionName) {
    // 默认选择城市
    console.log(cityId, regionName)
    auth.saveChooseAreaInfo({
      cityId,
      regionName: decodeURIComponent(regionName)
    })
  }

  if (pwy) {
    // 加密的 password 、 account
    const pwyStr = '?' + utils.decodeQuery(pwy)
    const pwyObj = utils.param2Obj(pwyStr)
    const { pad, acc } = pwyObj
    console.log(pwyObj, pwyStr)
    console.log(acc, '2account', auth.getLocAccount())
    if (acc !== auth.getLocAccount() && acc) {
      console.log('商户号不一样，清楚缓存')
      auth.removeAll()
      auth.clearAll()
    }
    acc && locAccount.set(acc)
    pad && locPassword.set(pad)
  }
  const isShare = location.href.includes('isShare=1')
  if (
    shareUrl &&
    (evn !== 'abc' || window.location.href.includes('hasPay') || isShare)
  ) {
    // 分享的操作
    const url = utils.decodeQuery(shareUrl)
    const query = utils.param2Obj(url)
    const { account, password } = query
    auth.getShareQuery(query)
    account && locAccount.set(account)
    password && locPassword.set(password)

    const _param = utils.deep(param)
    delete _param.shareUrl

    if (url.includes('isShare=2')) {
      // !需要联登的渠道才需要加 isShare = 2
      // !特殊处理 农行单独处理
      locSharePath.set(url)
    }
    const toPath =
      utils.getBaseUrl() + '?' + utils.obj2Param(_param) + '#' + url
    window.location.href = toPath
  } else {
    if (!isShare) {
      auth.getShareQuery({})
    }
  }
}

function replaceUrlToken() {
  const url = window.location.href
    .replace(window.location.origin, '')
    .replace(/token(Id)?=/, 'oldtk=' + ~~(Math.random() * 100))
  window.history.replaceState('', document.title, url)
}

// !建行不能加 viewport-fit=cover
function handleMate() {
  const name = 'viewport'
  let content =
    'width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no'

  if (!window.location.href.includes('VIEWPORT=1')) {
    content = content + ',viewport-fit=cover'
  }
  const meta = document.createElement('meta')
  meta.content = content
  meta.name = name
  document.getElementsByTagName('head')[0].appendChild(meta)
}
